import Vue from "vue";
import Vuex from "vuex";
import { get_song_detail, get_lyric } from "@/api/common";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    // 使用 play_state 来表示音频的播放状态
    playing: false,
    singer: [],
    song_name: "歌名",
    song_id: 0,
    imgUrl: "",
    duration: 1000,
    progress: 0,
    // 表示当前播放列表 id 集合
    play_list: [],
    // 表示当前播放歌曲的下标(第几首)
    song_idx: 0,
    // 歌词偏移
    offset: 0,
    // 歌词
    medisArray: [],
    // 是否拖动
    drag_status: false,
    // 滚动歌词
    scroll_lyric: true,
  },
  getters: {
    // 歌手拼接
    singer(state) {
      if (state.singer === []) {
        return [];
      }
      return state.singer.map((el) => el.name).join(" / ");
    },
  },
  mutations: {
    // 改变音频的播放状态
    change_state(state, is_playing) {
      state.playing = is_playing;
    },
    // 设置歌曲信息
    change_song(state, song_info) {
      state.song_name = song_info.name;
      state.song_id = song_info.id;
      state.imgUrl = song_info.imgUrl;
      state.singer = song_info.singer;
      state.duration = song_info.duration;
    },
    // 设置 播放列表
    set_play_list(state, list) {
      state.play_list = list;
    },
    change_idx(state, val) {
      state.song_idx = val;
    },

    // 改变播放或暂停
    change_playing(state, params) {
      state.playing = params;
    },
    // 播放进度
    change_progress(state, arg) {
      state.progress = arg;
    },
    // 歌词偏移
    change_offset(state, num) {
      state.offset = num;
    },
    // 歌词
    m_medisArray(state, arr) {
      state.medisArray = arr;
    },
    // 拖动触发
    change_drag_status(state, flg) {
      state.drag_status = flg;
    },
    // 改变歌词的滚动
    change_scroll_lyric(state, boolean) {
      state.scroll_lyric = boolean;
    },
  },
  actions: {
    // 歌曲详情
    async get_song_detail(context, id) {
      let song_detail = await get_song_detail(id);
      let current_song = song_detail.data.songs[0];
      let song_info = {
        singer: current_song.ar,
        id: current_song.id,
        imgUrl: current_song.al.picUrl,
        name: current_song.name,
        duration: current_song.dt,
      };
      // 将当前音频的相关信息存至 store, 歌名 ar id
      // 注: 点击播放时, 会将播放列表切换至当前歌曲的所在歌单, 方便后面做上一首,下一首的切换;
      context.commit("change_song", song_info);
    },
    // 获取歌词信息
    async get_song_lyric(context, id) {
      let lyric_data = await get_lyric(id);
      let lyric = lyric_data.data.lrc.lyric.split("\n");
      let medisArray = [];
      // 拆分 歌词和时间
      lyric.forEach((el) => {
        if (el.substring(el.indexOf("]") + 1)) {
          let time = el
            .substring(el.indexOf("[") + 1, el.indexOf("]"))
            .split(":");
          medisArray.push({
            t: Math.round(time[0]) * 60 + Math.round(time[1]),
            c: el.substring(el.indexOf("]") + 1),
          });
        }
      });
      // console.log(lyric);
      context.commit("m_medisArray", medisArray);
    },
  },
  modules: {},
});
